
bt.module({builder: function(bt) {
    var j$ = jQuery;
    var liveFall;
    var loading = false;

    var WarterFall = function(opts) {
        var defaultOptions = {
            "fallCount": 1,
            "fallClassPrefix": "col-"
        };
        this.opts = defaultOptions;
        for(i in opts) {
            this.opts[i] = opts[i];
        }
    };

    WarterFall.prototype.getShortestFall = function() {
        var shortestFall = j$('.' + this.opts.fallClassPrefix + '0');
        var minHeight = shortestFall.height();
        for(var i = 1; i < this.opts.fallCount; i ++) {
            var fall = j$('.' + this.opts.fallClassPrefix + i);
            if(minHeight > fall.height()) {
                minHeight = fall.height();
                shortestFall = fall;
            }
        }
        return shortestFall;
    };

    WarterFall.prototype.addItem = function (item) {
        var fall = this.getShortestFall();
        fall.append(j$(item));
    };

    var loadMoreLive = function(count) {
        if(loading) {
            return;
        }
        loading = true;
        count = count || 12;
        var before = j$(".live-contents").data("before");
        j$.ajax({
            url: "/explore/new_live_more/",
            data: "count=" + count + "&before=" + before,
            success: function(resp) {
                j$(".tmp-container").html(resp);
                addToWaterFall();
                j$(".live-contents").data("before", j$(".before").data("before"));
                j$(".before").remove();
                loading = false;
                j$(window).scroll(); 
            }
        });
    };

    var loadGroupLive = function(container, uid, count, before, wpid) {
        j$.ajax({
            url: "/explore/new_live_extend/",
            data: "uid=" + uid + "&count=" + count + "&before=" + before 
                + "&exclude_id=" + wpid,
            success: function(resp) {
                container.html(resp);
                container.removeClass("hidden");
                container.addClass("loaded");
                initLiveItemEvents(container);
            }
        });
    };

    var addToWaterFall = function() {
        var items = j$(".live-contents .tmp-container .live-item");
        for(var i = 0; i < items.length; i ++) {
            liveFall.addItem(items[i]);
            initLiveGroupEvents(items[i]);
        }
    };

    var _renderCommentHTML = function(comment) {
        var c = comment.comment;
        var custom_url = c.user.custom_url;
        if (custom_url == '') {
            custom_url = 'u/' + c.user.id;
        }
        var obj = j$(
        '<div class="comment-item cb first-comment-item">' +
        '    <div class="avatar fl pr">' +
        '        <a href="/' + custom_url + '">' +
        '            <img src="' + c.user.avatar_s + '" title="' + c.user.name + '" width="32" height="32"/>' +
        '            <div class="avatar-mask-32 pa"></div>' +
        '        </a>' +
        '    </div>' +
        '    <div class="name">' +
        '        <a href="/' + custom_url + '">' + c.user.name + '</a>' +
        '    </div>' +
        '    <div class="comment-content">' +
        '        <span>' + c.comment + '</span>' +
        '    </div>' +
        '    <div class="comment-meta">' +
        '        <div class="time fl">' +
        '            <span>' + c.date_added + '</span>' +
        '        </div>' +
        '        <div class="reply-btn fr" data-uid="' + c.user.id + '" data-uname="' + c.user.name + '">' +
        '            <a>回复</a>' +
        '        </div>' +
        '        <div class="cb"></div>' +
        '    </div>' +
        '</div>');
        return obj;
    };

    var initLiveItemEvents = function(obj) {
        obj = j$(obj);
        var _initReplyButton = function(o) {
            o.find(".reply-btn").click(function() {
                var formDiv = j$(this).parents(".info").find(".reply-form");
                formDiv.removeClass("hidden");
                formDiv.find("form").data("uid", j$(this).data("uid"));
                formDiv.find("input.text").val(
                    "回复" + j$(this).data("uname") + ": ");
                bt.misc.textboxFocus(formDiv.find("input.text"));
            });
        };
        obj.find(".photo img").load(function() {
            j$(this).fadeIn();
        });
        obj.find(".reply-form form").submit(function() {
            var form = j$(this);
            if(form.hasClass("sending")) {
                return;
            }
            form.addClass("sending");

            var url = form.attr("action");
            var data = form.serialize();
            form.find("input.text").attr("disabled", "disabled");
            var uid = form.data("uid");
            if(uid) {
                data += "&to=" + uid;
            }
            j$.ajax({
                url: url,
                type: "POST",
                data: data,
                success: function(resp) {
                    if(resp.error) {
                        alert(resp.error);
                    } else {
                        form.parents(".info").find(".comments-top").show();
                        form.parents(".info").find(".reply-top, .reply-action-bar").show();
                        var container = form.parents(".info").find(".comment-list");
                        var item = _renderCommentHTML(resp);
                        container.find(".comment-item").removeClass("first-comment-item");
                        container.show();
                        item.prependTo(container);
                        _initReplyButton(item);

                        // Change the count
                        bt.misc.modifyCount(form.parents(".info").find(".comment span.num"), 1);
                        bt.misc.modifyCount(form.parents(".info").find(".read-more span.num"), 1);

                        // Clear form
                        form.removeData("uid");
                        form.find("input.text").val("");
                        form.parents(".reply-form").addClass("hidden");
                    }
                },
                complete: function() {
                    form.removeClass("sending");
                    form.find("input.text").removeAttr("disabled");
                }
            });
            return false;
        });


        _initReplyButton(obj);
        obj.find(".need-login").click(function() {
            bt.misc.redirect_to_login();
        });
        obj.find(".add-comment, .add-reply-btn").click(function() {
            var formDiv = j$(this).parents(".info").find(".reply-form");
            formDiv.toggleClass("hidden");
            bt.misc.textboxFocus(formDiv.find("input.text"));
        });
        obj.find(".desc a").each(function() {
            j$(this).ThreeDots({
                max_rows: 1,
                alt_text_t: true,
                whole_word: false
            });
        });

        // Recommend button
        obj.find(".meta .like").click(function() {
            if (!BT_USER_ID) {
                bt.misc.redirect_to_login();
                return false;
            }
            if(j$(this).hasClass('ajax-loading')) {
                return false;
            }
            var _this = this;
            var recommended = j$(this).hasClass("liked");
            var url = j$(this).data("url");
            url += recommended? "delete_recommend/": "recommend/";
            j$(this).addClass('ajax-loading');
            j$.ajax({
                url: url,
                dataType: "json",
                type: "POST",
                success: function(resp) {
                    if(resp.error) {
                        alert(resp.error);
                    } else {
                        if(recommended) {
                            j$(_this).removeClass("liked");
                            bt.misc.modifyCount(j$(_this).find("span"), -1);
                        } else {
                            j$(_this).addClass("liked");
                            bt.misc.modifyCount(j$(_this).find("span"), 1);
                        }
                        refreshItemRecommendationPanel(j$(_this));
                    }
                },
                error: function(){
                    alert("操作失败，请稍候再试");
                },
                complete: function() {
                    j$(_this).removeClass('ajax-loading')
                }
            });
        });
    };

    var refreshItemRecommendationPanel = function(obj) {
        var url = "/explore/live/wp_recommendations/" + obj.data("wpid") + "/";
        j$.ajax({
            url: url,
            type: "POST",
            success: function(resp) {
                obj.parents(".info").find(".like-list").html(resp);
            }
        });
    };

    var initLiveGroupEvents = function(obj) {
        obj = j$(obj);
        initLiveItemEvents(obj);
        obj.find(".group-btn").click(function() {
            var group = j$(this).parents(".live-item").find(".grouped-items");
            if(!group.hasClass("loaded")) {
                var count = j$(this).data("count");
                var before = j$(this).data("before");
                var uid = j$(this).data("uid");
                var wpid = j$(this).data("wpid");
                loadGroupLive(group, uid, count, before, wpid);
            }
            group.toggleClass("hidden");
            j$(this).toggleClass("extended");
            if(j$(this).hasClass("extended")) {
                j$(this).removeAttr("href");
            } else {
                j$(this).attr("href", j$(this).data("href"));
            }
        });
    };

    var initLoadMoreLiveEvent = function() {
        j$(window).scroll(function() {
            var col = liveFall.getShortestFall();
            if(col.offset().top + col.height()
                - j$(window).scrollTop()
                - document.documentElement.clientHeight < 100) {
                loadMoreLive();
            }
        });
        
    };

    var initLoadMoreHotEvent = function() {
        j$("#load-more").click(function() {
            var _this = this;
            j$('#ajax-more').css("visibility", "visible");

            j$.ajax({
                url: "/explore/new_hot/grid/",
                data: "page=" + j$(_this).data("next"),
                success: function(resp) {
                    if(resp) {
                        j$(".hot-contents").append(resp);
                    } else {
                        j$("#load-more").slideUp();
                    }
                }
            }).always(function() {
                j$(_this).remove();
                initLoadMoreHotEvent();
                j$('.cover img').each(function(){
                    bt.misc.centerAlignImg(j$(this), 156, 278);
                });

                j$('.cover img').bind('load', function(){
                    bt.misc.centerAlignImg(j$(this), 156, 278);
                });

                j$(".item .info .name a").each(function() {
                    j$(this).ThreeDots({
                        max_rows: 1,
                        alt_text_t: true,
                        whole_word: false
                    });
                });

            });
        });
    };

    var refreshToTopBarPosition = function () {
        var scrollObj = j$(".to-top-bar");
        if(j$(window).scrollTop() > j$("#header").height()) {
            scrollObj.fadeIn();
        } else {
            scrollObj.hide();
        }
        var b = scrollObj.offset().top + scrollObj.outerHeight();
        var footerTop = j$("#footer").position().top;
        scrollObj.css("bottom", Math.max(0, j$(window).height() - j$("#footer").offset().top + j$(window).scrollTop()));
    };

    j$(document).ready(function() {
        if(j$(".tabs .live").hasClass("nav-current")) {
            // Live page
            liveFall = new WarterFall({
                fallCount: 3,
                fallClassPrefix: "col-"
            });
            addToWaterFall();
            initLoadMoreLiveEvent();

            // 兼容多浏览器
            var _body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');
            j$(".to-top").click(function() {
                _body.animate({"scrollTop": 0}, 100);
            });
            j$(window).scroll(function() {
                refreshToTopBarPosition();
            });

            j$(".photo img").each(function() {
                j$(this).fadeIn();
            });

            j$(".photo img").load(function() {
                j$(this).fadeIn();
            });
        } else {
            // HOT page
            if(j$(".tabs .slides").hasClass("hot-nav-slides-current")) {
                // HOT Slides page
                var _refreshHotTrips = function() {
                    var container = j$(".hot-trips-candidates");
                    j$(".hot-trips .item").hide()
                        .removeClass("first")
                        .appendTo(container);
                    var len = container.find(".item").length;
                    for(var i = 0; i < 4; i ++, len --) {
                        var index = Math.floor(Math.random() * len);
                        var obj = j$(container.find(".item")[index]);
                        if(i == 0) {
                            obj.addClass("first");
                        }
                        obj.appendTo(j$(".hot-trips")).fadeIn();
                    }
                    j$(".hot-trips .info .name a").each(function() {
                        j$(this).ThreeDots({
                            max_rows: 1,
                            alt_text_t: true,
                            whole_word: false
                        });
                    });
                    j$('.hot-trips .cover img').each(function(){
                        bt.misc.centerAlignImg(j$(this), 64, 64);
                    });

                    j$('.hot-trips .cover img').bind('load', function(){
                        bt.misc.centerAlignImg(j$(this), 64, 64);
                    });
                };
                j$(".scrollable").scrollable().bind('onSeek', function() {
                    _refreshHotTrips();
                });
                _refreshHotTrips();

                j$('.top-trips .cover img').each(function(){
                    bt.misc.centerAlignImg(j$(this), 564, 910);
                });

                j$('.top-trips .cover img').bind('load', function(){
                    bt.misc.centerAlignImg(j$(this), 564, 910);
                });

                j$('.hot-trips .cover img').each(function(){
                    bt.misc.centerAlignImg(j$(this), 64, 64);
                });

                j$('.hot-trips .cover img').bind('load', function(){
                    bt.misc.centerAlignImg(j$(this), 64, 64);
                });
            } else {
                // HOT Grid page
                j$('.cover img').each(function(){
                    bt.misc.centerAlignImg(j$(this), 156, 278);
                });

                j$('.cover img').bind('load', function(){
                    bt.misc.centerAlignImg(j$(this), 156, 278);
                });

                j$(".item .info .name a").each(function() {
                    j$(this).ThreeDots({
                        max_rows: 1,
                        alt_text_t: true,
                        whole_word: false
                    });
                });

                initLoadMoreHotEvent();

                var _body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');
                j$(".to-top").click(function() {
                    _body.animate({"scrollTop": 0}, 100);
                });
                j$(window).scroll(function() {
                    refreshToTopBarPosition();
                });
            }
        }
    });

}});
